﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Printing;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.ComponentModel;
using System.Windows.Threading;

namespace CjcPhotoPrint.Exporters
{
	public class Print : Exporter
	{
		public override void Export( IEnumerable<Transformable> transformables, Dispatcher dispatcher )
		{
			var dialog = new PrintDialog
			{
				MinPage = 1,
				MaxPage = (uint)transformables.Count()
			};

			if ( (bool)dialog.ShowDialog() )
			{
				var capabilities = dialog.PrintQueue.GetPrintCapabilities( dialog.PrintTicket );
				var pageArea = capabilities.PageImageableArea;

				var images = GetImages(
					transformables,
					new Size( pageArea.OriginWidth, pageArea.OriginHeight ),
					new Size( pageArea.ExtentWidth, pageArea.ExtentHeight ) ).ToArray();

				var worker = new BackgroundWorker();

				worker.DoWork += delegate
				{
					images.AsParallel().ForAll( i =>
					{
						dispatcher.BeginInvoke( (Action)delegate
						{
							dialog.PrintVisual( i.Value, i.Key );
						} );
					} );

					dispatcher.BeginInvoke( (Action)delegate
					{
						MessageBox.Show( "Printing complete" );
					} );
				};

				worker.RunWorkerAsync();
			}
		}

		protected IEnumerable<KeyValuePair<string, TransformedImage>> GetImages(
			IEnumerable<Transformable> transformables,
			Size origin,
			Size extent )
		{
			foreach ( var transformable in transformables )
			{
				var image = new TransformedImage { Drawing = transformable.Drawing };

				var pageAspect = extent.Width / extent.Height;

				if ( ( transformable.AspectRatio > 1 ) != ( pageAspect > 1 ) )
				{
					image.LayoutTransform = new RotateTransform( 90, 0.5, 0.5 );
				}

				var size = new Size( extent.Width, extent.Height );

				image.Measure( size );
				image.Arrange( new Rect( new Point( origin.Width, origin.Height ), size ) );

				yield return new KeyValuePair<string, TransformedImage>( transformable.Name, image );
			}
		}
	}
}